import router from "@/router/index"
import store from "@/store"

router.beforeEach((to, from, next) => {
    // 白名单
    const whiteList = ['/login']
    let token = store.getters.GET_TOKEN;
    let hasRoutes = store.state.hasRoutes;
    // 获取菜单
    let menulist = store.getters.GET_MENU_LIST
    // 是否放行
    if (token) {
        // false 没有被初始化
        console.log('hasRoutes:', hasRoutes)
        if (!hasRoutes) {
            // 开始初始化路由
            console.log('开始初始化路由')
            bindRoute(menulist)
            store.commit('SET_HAS_ROUTER', true)
        }
        next();
    } else {
        // 是否在白名单里
        if (whiteList.includes(to.path)) {
            next();
        } else {
            next("/login");
        }
    }
})
/**
 * 初始化路由
 * @param {Object} menuList 
 */
const bindRoute = (menuList) => {
    let newRouter = router.options.routes
    // 遍历菜单
    menuList.forEach(menu => {
        // 判断是否有子节点
        if (menu.children) {
            menu.children.forEach(m => {
                // 菜单转成路由
                let route = menuToRoute(m, menu.name)
                if (route) {
                    newRouter[0].children.push(route)
                }
            })
        }
    })
    newRouter.forEach(route => {
        router.addRoute(route)
    })
    console.log(menuList)
}
/**
 * 
 * @param {Object} menu 菜单 
 * @param {string} parentName 父节点名字
 * @returns 返回一个路由
 */
const menuToRoute = (menu, parentName) => {
    // 不是一个地址
    if (!menu.component) {
        return null
    } else {
        // 组装路由
        let route = {
            path: menu.path,
            name: menu.name,
            meta: {
                parentName: parentName
            }
        }
        route.component = () => import('@/views/' + menu.component + '.vue')
        return route
    }

}
